package com.teamclub.util.files;

import com.google.common.collect.Lists;
import com.teamclub.util.libs.F;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * Created by ilkkzm on 17-10-13.
 */
public class ExcelImporter {
    private File importFile;
    private Integer sheetIdx;
    private Integer titleLines;
    private List<String> keys;
    private List<String> content;
    private XSSFWorkbook wb = null;
    private XSSFSheet sheet = null;

    public ExcelImporter(File file) {
        this.importFile = file;
        this.sheetIdx = 0;
        this.titleLines = 1;
    }

    public void setSheetIdx(int i) {
        this.sheetIdx = i;
    }

    public void readValues(F.Function<List<String>, String> func) throws Throwable{
        List<String> lists = Lists.newArrayList();
        InputStream inp = null;
        try {
            inp = new FileInputStream(this.importFile);
            XSSFWorkbook wb = new XSSFWorkbook(inp);
            XSSFSheet sheet = wb.getSheetAt(this.sheetIdx);
            for(int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum++) {
                StringBuilder sb = new StringBuilder();
                XSSFRow xssfRow = sheet.getRow(rowNum);
                for(int cellNum = xssfRow.getFirstCellNum() ; cellNum <= xssfRow.getLastCellNum(); cellNum++) {
                    sb.append(getValue(xssfRow.getCell(cellNum))).append(",");
                }
                lists.add(sb.toString());
            }
            func.apply(lists);
        } finally {
            if(inp != null) {
                inp.close();
            }
        }
    }

    public String getValue(XSSFCell xssfCell) {
        if(null == xssfCell) return "";
        else if(xssfCell.getCellType() == xssfCell.CELL_TYPE_BOOLEAN) return String.valueOf(xssfCell.getBooleanCellValue());
        else if(xssfCell.getCellType() == xssfCell.CELL_TYPE_NUMERIC) return String.valueOf(xssfCell.getNumericCellValue());
        else return String.valueOf(xssfCell.getStringCellValue());
    }

    public static void main(String[] args) throws Exception{
        File file = new File("/tmp/1508121839831-0/haha.xls");
        ExcelImporter excelImporter = new ExcelImporter(file);
        try {
            excelImporter.readValues(new F.Function<List<String>, String>() {
                @Override
                public String apply(List<String> contents) throws Throwable {
                    for(String content: contents) {
                        System.out.println(content);
                    }
                    return "";
                }
            });
        } catch (Throwable t) {
            t.printStackTrace();
        }

    }
}
